<?php

class Vega_Dao
{
    
    protected static $_loader = null;
    
    protected static $_registry = array();
    
    protected static $_db;
    
    
    private function __construct()
    {
        // noone can create an instance
    }
    
    
    public static function setDb($db)
    {
        self::$_db = $db;
    }

    /**
     * Returns the default Vega_Db object
     *
     * @return Vega_Db_Abstract
     */
    public static function getDb()
    {
        return self::$_db;
    }

    /**
     * Sets the loader
     *
     * @param Vega_Loader $loader
     */
    public static function setLoader(Vega_Loader $loader)
    {
        self::$_loader = $loader;

        // default daos path
        self::$_loader->setDir('dao', 'framework' . DIRECTORY_SEPARATOR . 'daos', false);
    }


    /**
     * Factory a Vega_Dab_Table object
     *
     * @param string $table
     * @param Vega_Db_Abstract $db
     * @return Vega_Dao_Table
     */
    public static function factory($table, $db = null)
    {   
        if (isset(self::$_registry[$table]))
        {
            return self::$_registry[$table];
        }
        
        $tablePath = str_replace('_', DIRECTORY_SEPARATOR, $table);

        try {
            self::$_loader->load('dao', $tablePath . '.dao.php');
        } catch (Vega_Loader_Exception $e) {
            require_once 'Vega/Dao/Exception.php';
            echo $e->getMessage();
            throw new Vega_Dao_Exception('Could not load DAO class [table: ' . $table . ']. Path: ' . $tablePath);
        }
        
        $className = ucfirst($table) . 'Dao';

        if (null == $db)
        {
            $tableObject = new $className(self::$_db);
        }
        else
        {
            $tableObject = new $className($db);
        }
        
        self::$_registry[$table] = $tableObject;
        return $tableObject;
    }
}

